/*
 * @Description:
 * @Author: Cxy
 * @Date: 2025-04-21 15:58:55
 * @LastEditors: Cxy
 * @LastEditTime: 2025-05-23 18:41:46
 * @FilePath: \xy-admin\docs\.vitepress\theme\demo\plugin.ts
 */

import path, { resolve } from 'path'
import fs from 'fs'
import type { MarkdownRenderer } from 'vitepress'
import { highlight, initHighlighter } from '../../utils/highlight.ts'

initHighlighter().catch(err => {
  console.error('插件--Shiki--加载失败', err)
})

interface ContainerOpts {
  marker?: string | undefined
  validate?(params: string): boolean
  render?: MarkdownRenderer['renderer']['rules']['container']
}

const highlightVue = (str: string, yuyan: string) => {
  if (!str || str.trim() === '') {
    return ''
  }
  return `
    <summary>查看代码</summary>
    <div class="language-vue">
      <button title="复制代码" class="copy"></button>
      <span class="lang">${yuyan}</span>
      ${highlight(str, yuyan)}
    </div>
  `
}

export default (): ContainerOpts => {
  return {
    validate(params) {
      return !!params.trim().match(/^demo\s*(.*)$/)
    },

    render(tokens, idx) {
      const m = tokens[idx].info.trim().match(/^demo\s*(.*)$/)
      if (tokens[idx].nesting === 1) {
        const yuyan = m?.[1] || ''
        const sourceFileToken = tokens[idx + 2]
        let source = ''
        const sourceFile = sourceFileToken.children?.[0].content ?? ''
        if (sourceFileToken.type === 'inline') {
          source = fs.readFileSync(
            path.resolve(resolve(__dirname, '../../../'), 'elecomponents', `${sourceFile}.${yuyan}`),
            'utf-8'
          )
        }
        if (!source) throw new Error(`Incorrect source file: ${sourceFile}`)
        return `
                  <Demo
                    source="${encodeURIComponent(highlightVue(source, yuyan))}" 
                    path="${sourceFile}"
                    yuyan="${yuyan}"
                  >
                `
      } else {
        return '</Demo>'
      }
    }
  }
}
